

%% observed and predicted worldwide prevalence of democracy
pD=(1:T)'; pD_hat=pD;
for t=1:T
    pD(t)=sum(D(M(:,t)==1,t))/sum(M(:,t));
    pD_hat(t)=sum(D_hat(M(:,t)==1,t))/sum(M(:,t));
end

if exist('NL','var')~=1
    writetable(table(years,pD,pD_hat),['../../Figures/Figure_1/resultsK',num2str(K),'.csv'])
else
    writetable(table(years,pD,pD_hat),['../../Figures/Figure_1/resultsK',num2str(K),'nl.csv'])
end


%% observed and predicted prevalence of democracy by region:
% America: 2-165
% Europe: 200-255,290,305,310-317,325,339-370,375-390
% Africa: 404-625,651
% Asia-Oceania: 371-373,630-645,652-705,710-740,750-771,775,780-790,800-920
ccodes.region=ccodes.cnames;
for n=1:size(ccodes,1)
    if isempty(setdiff(ccodes.ccodes(n),2:165))
        ccodes.region(n)={'AME'};
    elseif isempty(setdiff(ccodes.ccodes(n),[200:255,290,305,310:317,325,339:370,375:390]))
        ccodes.region(n)={'EUR'};
    elseif isempty(setdiff(ccodes.ccodes(n),[404:625,651]))
        ccodes.region(n)={'AFR'};
    else
        ccodes.region(n)={'ASO'};
    end
end

pD_AME=pD; pDh_AME=pD;
pD_EUR=pD; pDh_EUR=pD;
pD_AFR=pD; pDh_AFR=pD;
pD_ASO=pD; pDh_ASO=pD;
for t=1:T
    pD_AME(t)=sum(D(strcmp(ccodes.region,'AME')&M(:,t)==1,t))/sum(strcmp(ccodes.region,'AME')&M(:,t)==1);
    pDh_AME(t)=sum(D_hat(strcmp(ccodes.region,'AME')&M(:,t)==1,t))/sum(strcmp(ccodes.region,'AME')&M(:,t)==1);
    pD_EUR(t)=sum(D(strcmp(ccodes.region,'EUR')&M(:,t)==1,t))/sum(strcmp(ccodes.region,'EUR')&M(:,t)==1);
    pDh_EUR(t)=sum(D_hat(strcmp(ccodes.region,'EUR')&M(:,t)==1,t))/sum(strcmp(ccodes.region,'EUR')&M(:,t)==1);
    pD_AFR(t)=sum(D(strcmp(ccodes.region,'AFR')&M(:,t)==1,t))/sum(strcmp(ccodes.region,'AFR')&M(:,t)==1);
    pDh_AFR(t)=sum(D_hat(strcmp(ccodes.region,'AFR')&M(:,t)==1,t))/sum(strcmp(ccodes.region,'AFR')&M(:,t)==1);
    pD_ASO(t)=sum(D(strcmp(ccodes.region,'ASO')&M(:,t)==1,t))/sum(strcmp(ccodes.region,'ASO')&M(:,t)==1);
    pDh_ASO(t)=sum(D_hat(strcmp(ccodes.region,'ASO')&M(:,t)==1,t))/sum(strcmp(ccodes.region,'ASO')&M(:,t)==1);
end

if exist('NL','var')~=1
    writetable(table(years,pD_AME,pDh_AME,pD_EUR,pDh_EUR,pD_AFR,pDh_AFR,pD_ASO,pDh_ASO),...
        ['../../Appendix_A2/Figure_A2/results_regionK',num2str(K),'.csv'])
else
    writetable(table(years,pD_AME,pDh_AME,pD_EUR,pDh_EUR,pD_AFR,pDh_AFR,pD_ASO,pDh_ASO),...
        ['../../Appendix_A2/Figure_A2/results_regionK',num2str(K),'nl.csv'])
end



